// pages/user/user.js
import painter from '../../utils/painterImage/image'

let app = getApp();
import Toast from '../../miniprogram/miniprogram_npm/vant-weapp/toast/toast'
import Dialog from '../../miniprogram/miniprogram_npm/vant-weapp/dialog/dialog'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: null,
    tabCartTotal: '',
    showLogin: false,//登录弹框
    counts: {
      daifukuan: '',
      daipeison: '',
      yifahuo: '',
      yishoushuo: '',
      yiwancheng: '',
      tangshi: '',
      waimai: '',
      ziti: '',
    },//订单角标
    totalCommission: 0,//门店累计佣金
    income: 0,//门店今日预计收益
    isPickMoney: false,//控制提现弹框
    balance: 0,//余额
    assistMode: false,
    checkHide: '',//0放开商户入驻  1隐藏商户入驻
    shopAfterInfo: false,
    centerObj: '',
    vipUpShow: false,//会员升级弹框
    vipUpPrice: '',
    vipUpRadio: 'wx',
    collectQr: '',//收款码
    collectQrShow: false,//收款码弹框
    isDelivery: false,//配送员身份
  },

  //检查配送员
  checkDelivery(){
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/deliveryman/query',
      data: {
        userId: _this.data.user.id
      }
    }).then(res =>{
      if(res.data.deliveryman){
        if(res.data.deliveryman.auditStatus == 1){
          _this.setData({ isDelivery: true})
        }
      }
    })
  },

  //门店累计佣金、今日预计收益
  teamSmallData(){
    let _this = this;
    if(_this.data.user.isteam != 3) return;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/commission/total',
      data: {
        memberId: _this.data.user.id,
        isGrant: 1
      },
      load: 0
    }).then((res) => {
      _this.setData({
        totalCommission: res.data.data
      })
    })
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/commander/income/expect',
      data: {
        memberId: _this.data.user.id,
        isGrant: 1
      },
      load: 0
    }).then((res) => {
      _this.setData({
        income: res.data.data
      })
    })
  },

  //获取订单角标
  getOrderCount(){
    let _this = this;

    app.requestUrl({
      method: 'GET',
      url: '/wxapi/order/count',
      data: {
        memberId: _this.data.user.id,
      },
      load: 0
    }).then((res) => {
      _this.data.counts = {};//清空数据
      //商城订单数据统计
      res.data.data.forEach(item => {
        if (item.status === 0)
          _this.data.counts.daifukuan = item.num;
        else if (item.status === 1)
          _this.data.counts.daipeison = item.num;
        else if (item.status === 2)
          _this.data.counts.yifahuo = item.num;
        else if (item.status === 3)
          _this.data.counts.yishoushuo = item.num;
        else if (item.status === 6)
          _this.data.counts.yiwancheng = item.num;
      });
      //餐饮订单数据统计
      res.data.canyinData.forEach(item => {
        if (item.cateringType === 1)
          _this.data.counts.tangshi = item.num;
        else if (item.cateringType === 2)
          _this.data.counts.waimai = item.num;
        else if (item.cateringType === 3)
          _this.data.counts.ziti = item.num;
      });
      _this.setData({
        counts: _this.data.counts
      })
    })
  },

  //获取用户信息，积分字段
  getAllUserInfo(){
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/member',
      data: {
        id: _this.data.user.id,
        getShop: true
      },
      load: 0
    }).then((res) => {
      _this.data.user = res.data.data;
      _this.data.user.supplier = res.data.supplier;
      _this.data.user.points = res.data.points;

      if(res.data.shop)
        // wx.setStorageSync('shopInfo', JSON.stringify(res.data.shop))
      wx.setStorageSync('userInfo', JSON.stringify(_this.data.user))
      _this.setData({
        user: _this.data.user,
        points:res.data.points,
      })
    })
  },

  //接收提现组件传值，控制弹框
  isPickMoneyCollect(event){
    this.setData({
      isPickMoney: event.detail
    })
  },
  //接收提现组件传值，改变余额
  userCollect(event){
    this.setData({
      user: event.detail
    })
  },
  //提现打开弹框
  pickMonitor(){
    if(this.data.user.id == null){
      this.setData({ showLogin: true })
      return;
    }

    this.setData({
      isPickMoney: true
    })
  },

  //会员升级价格
  getVipUpPrice(){
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/mem/getVippriceBycentreId',
      data: {centreId: _this.data.user.centreId},
      load: 0,
    }).then(res =>{
      _this.setData({
        vipUpPrice: res.data.data
      })
    })
  },
  //会员升级弹框
  vipUpShow(){
    this.setData({
      vipUpShow: true
    })
  },
  vipUpRadioChange(event){
    this.setData({
      vipUpRadio: event.detail
    })
  },
  //会员升级支付
  vipUpPayment(){
    let _this = this;
    if(_this.data.vipUpRadio == 'wx'){
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/vip/wxpay',
        data: {
          memberId: _this.data.user.id,
          openId: _this.data.user.openid,
          code: '',
          centreId: _this.data.user.centreId,
        }
      }).then((res)=>{
        let party = {};
        let respData = res.data.data.respData;
        if(respData){
          party.addId = respData.payAppId;
          party.nonceStr = respData.paynonceStr;
          party.package = respData.payPackage;
          party.paySign = respData.paySign;
          party.signType = respData.paySignType;
          party.timeStamp = respData.payTimeStamp;
        }
        //兼容微信支付，第三方支付
        let last = respData ? party : res.data.data;
        //发起微信支付
        wx.requestPayment({
          ...last,
          success(res) {
            _this.getAllUserInfo();
            Toast('支付成功');
          },
          fail(res) {
            Toast('支付失败/vip/wxpay');
          }
        })
      })
    } else if(_this.data.vipUpRadio == 'yu'){
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/vip/yupay',
        data: {
          memberId: _this.data.user.id,
          code: '',
        }
      }).then((res)=>{
        if(res.data.code == 0){
          _this.getAllUserInfo();
          if(res.data.data == 0){
            Toast('余额不足');
          }else{
            Toast('会员升级成功');
          };
        }
          
        else
          Toast(res.data.msg);
      })
    }
    this.setData({
      vipUpShow: false
    })
  },
  
  //修改用户信息
  toSetting(){
    wx.navigateTo({
      url: '/sub/user/setting/setting'
    })
  },
  //提现记录
  toPickMoneyList(){
    if(this.data.user.id == null){
      this.setData({ showLogin: true })
      return;
    }

    wx.navigateTo({
      url: '/sub/user/pick-money-list/pick-money-list'
    })
  },
  //余额列表
  toBalanceList(){
    if(this.data.user.id == null){
      this.setData({ showLogin: true })
      return;
    }

    wx.navigateTo({
      url: '/sub/user/balance-list/balance-list'
    })
  },
  //我的餐饮订单
  toRestaurantOrderList(event){
    console.log(event);
    if(this.data.user.id == null){
      this.setData({ showLogin: true })
      return;
    }

    wx.navigateTo({
      url: '/sub/user/canyin-orderList/canyin-orderList?active=' + event.currentTarget.dataset.active + '&orderType=' + event.currentTarget.dataset.type
      + '&cateringtype=' + event.currentTarget.dataset.cateringtype
    })
  },
  //我的订单
  toOrderList(event){
    console.log(event);
    if(this.data.user.id == null){
      this.setData({ showLogin: true })
      return;
    }

    wx.navigateTo({
      url: '/pages/user/order-list/order-list?active=' + event.currentTarget.dataset.active + '&orderType=' + event.currentTarget.dataset.type
    })
  },
  //我的预约订单
  toYuYueOrderList(event){
    if(this.data.user.id == null){
      this.setData({ showLogin: true })
      return;
    }

    wx.navigateTo({
      url: '/sub/user/yuyue-orderList/yuyue-orderList?active=' + event.currentTarget.dataset.active + '&orderType=' + event.currentTarget.dataset.type
    })
  },
  //我的拼团
  toOrderListSpell(event){
    wx.navigateTo({
      url: '/pages/user/order-list-spell/order-list-spell?active=' + event.currentTarget.dataset.active
    })
  },
  // 我的秒杀
  toOrderListMiaosha(event){
    wx.navigateTo({
      url: '/pages/user/order-list-miaosha/order-list-miaosha?active=' + event.currentTarget.dataset.active
    })
  },
  // 我的预售
  toOrderListYushou(event){
    wx.navigateTo({
      url: '/pages/user/order-list-yushou/order-list-yushou?active=' + event.currentTarget.dataset.active
    })
  },
  // 我的预约
  toOrderListYuyue(event){
    wx.navigateTo({
      url: '/pages/user/order-list-yuyue/order-list-yuyue?active=' + event.currentTarget.dataset.active
    })
  },
  // 退款/售后
  toShopAfter(){
    wx.navigateTo({
      url: '/sub/user/shop-after-list/index?id='+this.data.user.teamid
    })
  },

  loginClick(){
    this.setData({
      showLogin: true
    })
  },
  //接收登录弹框组件传值
  showLoginFun(event){
    this.setData({
      showLogin: event.detail
    })
  },

  isAssistMode() {
    const assistMode = wx.getStorageSync('assistMode');
    return (assistMode && assistMode > 0);
  },

  setAssistMode(mode) {
    if (mode) {
      wx.setStorageSync('assistMode', 1);
    } else {
      wx.removeStorage({key: 'assistMode'});
    }
  },

  toAssistBuy() {
    if (this.data.assistMode) {
        this.setData({assistMode: false})
        this.setAssistMode(false);
    } else {
        this.setAssistMode(true);
        //this.$router.push({name: 'home'});
        wx.switchTab({url: '/pages/index/index'})
    }
  },

  //退出登录
  exitLogin(){
    Dialog.confirm({
      title: '提示',
      message: '确定退出登录？'
    }).then(()=>{
      let mid = app.globalData.tempMid;
      let refOpenId = wx.getStorageSync('shareOpenid');
      wx.clearStorageSync();
      app.globalData.tempMid = mid;
      wx.setStorageSync('shareOpenid',refOpenId);
      wx.switchTab({
        url: '/pages/index/index',
      })
    }).catch(()=>{})
  },

  //是否屏蔽商户入驻
  checkShowShow(){
    let _this = this;
    if(_this.data.user.centreId == null) return;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/centre/getCentreById',
      data: {
        centreId: _this.data.user.centreId
      }
    }).then(res =>{
        _this.setData({
          checkHide: res.data.data.hide
        })
    })
  },

  //商户后台信息
  centerInfo () {
    let _this = this
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/center/info',
      data: {
        mid: _this.data.user.isCentre == 1 ? _this.data.user.id : ''
      }
    }).then(res => {
      _this.setData({
        centerObj: res.data.data
      })
    })
  },

  //商户后台信息框
  shopAfterInfoMonitor(){
    let _this = this;
    _this.setData({shopAfterInfo: !_this.data.shopAfterInfo})
  },

  //收款码弹框
  collectQrMonitor(){
    let _this = this;
    _this.setData({
      collectQrShow: !_this.data.collectQrShow
    })
    if(_this.data.collectQrShow){
      let path = 'sub/user/shop-order-list/index'
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/qr/appCode',
        data: {
          flag: 4,
          url: path,
          upShopId: _this.data.user.upshopTid,
          upCentreId: '',
          goodsId: '',
          centreId: _this.data.user.centreId,
          cd: '',
          userId: _this.data.user.id,
        },
        header: {
          'Content-Type': 'application/json;charset=UTF-8',
          'Authorization': wx.getStorageSync('authToken') || 'empty-token'
        },
      }).then(res =>{
        _this.setData({
          collectQr: res.data.date
        })
      })
    }
  },
  
  //去充值
  toRechargeMoney(){
    if(this.data.user.id == null){
      this.setData({ showLogin: true })
      return;
    }
    wx.navigateTo({
      url: '/sub/user/recharge-money/recharge-money'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;
    _this.setData({
      user: app.getUser(),
      assistMode: _this.isAssistMode(),
      balance: app.getUser().credit2,
      tabCartTotal: wx.getStorageSync('cartTotal'),
    })
    if(_this.data.user.id == null) return;

    _this.getAllUserInfo();
    _this.getOrderCount();
    _this.teamSmallData();
    _this.centerInfo();
    _this.getVipUpPrice();
    _this.selectComponent('#cash-withdrawal').getBankList()
    _this.checkShowShow();
    _this.checkDelivery();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var _this = this;
    let share = app.getShareData();
    let shareTitle = share.shareTitle.split('{')[0] + _this.data.shop.tXiaoqu + share.shareTitle.split('}')[1]
    return {
      title: shareTitle,
      path: '/pages/index/index?heShopId=' + app.getShop().id + '&heCentreId=' + _this.data.user.centreId,//用户A分享时带上用户A的团长id，用户B点击链接直接绑定用户A的团长
      success: function () {

      },
      fail: function () {
        wx.showToast({ title: '分享失败', icon: 'none' })
      }
    }
  },
  jumpUserInvite:function(){
    wx.navigateTo({
      url: '/sub/user/user-invite/user-invite'
    })
  },
  jumpCoupon:function(){
    wx.navigateTo({
      url: '/sub/user/coupon-list/coupon-list'
    })
  },
  //分销中心
  jumpDistributionCenter:function(){
    wx.navigateTo({
      url: '/sub/user/distributionCenter/distributionCenter'
    })
  },
})
